package top.zackyoung.jpa.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.zackyoung.jpa.dao.SysRoleRepository;
import top.zackyoung.jpa.dao.SysUserRepository;
import top.zackyoung.jpa.entity.SysRole;
import top.zackyoung.jpa.entity.SysUser;
import top.zackyoung.jpa.service.UserService;

import java.util.List;
import java.util.stream.Stream;

/**
 * @author: ZackYoung
 * @time: 2020/9/18
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    SysUserRepository userRepository;
    @Autowired
    SysRoleRepository roleRepository;
    @Override
    public void oneKeyAdd() {
        // 创建用户
        String[] userNames = {"张三","李四","王五","小六","胜七"};
        for (String userName : userNames) {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(userName);
            userRepository.save(sysUser);
        }

        // 创建角色
        String[] roleNames = {"董事长","总监","经理","职员"};
        for (String roleName : roleNames) {
            SysRole sysRole = new SysRole();
            sysRole.setRoleName(roleName);
            roleRepository.save(sysRole);
        }
    }

    @Override
    public Stream<SysUser> findAll(Integer page, Integer limit) {
        //Jpa 分页查询
        //通过订单日期进行排序，orderdate 是OrderBean 中的变量，不是数据库中的字段（*）
        Sort sort = Sort.by(Sort.Direction.ASC,"userId");

        // page 从 0 开始 ，3 是指每个page的大小，这个意思是按照订单日期排序分页查询，每次查询三个数据
        Pageable pageable = PageRequest.of(page,limit,sort);

        return userRepository.findAll(pageable).get();
    }

    @Override
    public List<SysUser> findAll() {
        return userRepository.findAll();
    }
}
